package com.musicstore.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.musicstore.biz.UserBiz;

@Controller
public class AdminController {
	@Autowired
	private UserBiz userBiz;
	//多文件上传
	@RequestMapping("/upload")
	public String upload(){
		
		return "upload";
	}
	@RequestMapping("/uploadFiles")
	public String uploadFiles(@RequestParam(value="attachs",
			required=false)MultipartFile [] attachs,HttpServletRequest request){
		String path = request.getServletContext().getRealPath("files");//得到文件夹路径
		for(MultipartFile multipartFile:attachs){
			if(!multipartFile.isEmpty()){
				String filename = path+"/"+multipartFile.getOriginalFilename();
				System.out.println(filename);
				File file = new File(filename);
				System.out.println(file.toString());
				//写入文件
				try {
					multipartFile.transferTo(file);
				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				System.out.println("上传成功！");
			}
		}
		return "upload";
	}
	//文件下载
	@RequestMapping("/download")
	public void download(String filename,HttpServletRequest request,HttpServletResponse response){
		//设置编码
		response.setCharacterEncoding("utf-8");
		//设置响应
		response.setContentType("multipart/form-data");
		//设置响应资源
		response.setHeader("content-disposition","attachement;filename="+filename);
		//获取文件的物理路径
		String path=request.getSession().getServletContext().getRealPath("CoverImages/"+filename);
		File file = new File(path);
		try {
			FileInputStream inputStrem = new FileInputStream(file);
			OutputStream out = response.getOutputStream();
			byte [] b = new byte[1024];
			int length;
			while((length=inputStrem.read(b))>0){
				//写入到输出流
				out.write(b,0,length);
			}
			inputStrem.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
